<?php
namespace App\Models\Mongo;

/**
 * Class {$className}
 * {$tableComment}
 * @package App\Models
 * @author  {$author}
 * @since   {$currentDate}
 */

use App\Library\Framework\Helper;

class {$className} extends BaseModel
{
    /**
     * 表名
     */
    protected $collection = '{$table}';

    /**
     * 缓存组名
     */
    static protected $cacheTag = '{$table}';

    /**
     * 可入库字段
     */
    protected $fillAble = {$fields};

    protected $guarded = ['_id'];
    /**
     * 隐藏输出字段
     */
    protected $hidden = ['_id'];

    public function getFillAble()
    {
        return $this->fillAble;
    }

    /**
    * 字段类型
    * @var array
    */
    protected $casts = {$casts};

    //Model RelationShip

    /**
     * 聚集查询
     * @param $query
     * @param $params
     * @return mixed
     */
    public function scopeFilter($query, $params)
    {
        $params = Helper::preScopeFilter($this->casts, $params);
        {$scopeFilterString}

        return $query;
    }

    /**
     * @title   分页及导出查询
     * @desc    分页及导出数据查询
     * @version 1.0.0
     * @level 1
     * @author {$author}
     * @package App\Models\Mongo
     * @since {$currentDate}
     * @params  type filedName required?
     * @param array $params
     * @return mixed
     * @returns
     * []
     * @returns
     */
    static public function getList(array $params)
    {
        $pageSize = isset($params['per_page']) && $params['per_page'] ? intval($params['per_page']) : 10;
        $page = isset($params['page']) ? intval($params['page']) : 1;


        $cacheName = __METHOD__ . var_export($params, TRUE);
        $data      = app('cache')->tags(self::$cacheTag)->get($cacheName);

        if (!$data) {
            if (isset($params['sortField']) && isset($params['sort'])) {
                $orderField = $params['sortField'];
                $orderType  = $params['sort'];
            } else {
                $orderField = 'createtime';
                $orderType  = 'desc';
            }

            $sqlObj = self::Filter($params);
            $sqlObj->orderBy($orderField, $orderType);

            if (isset($params['_export']) && $params['_export'] == 1) {
                $data = $sqlObj->get();
            } else {
                $data = $sqlObj->Paginate($pageSize, ['*'], 'page', $page);
            }
            app('cache')->tags(self::$cacheTag)->put($cacheName, $data, Config('cache.expireTime'));
        }

        return $data;
    }

    /**
     * @title   根据id查询数据
     * @desc    根据id查询数据
     * @version 1.0.0
     * @level 1
     * @author {$author}
     * @package App\Models\
     * @params  char id 主键  是
     * @param id
     * @return mixed
     * @returns
     * {}
     * @returns
     */
    static public function getById($id = NULL)
    {
        $cacheName = __METHOD__ . var_export($id, TRUE);
        $data      = app('cache')->tags(self::$cacheTag)->get($cacheName);
        if (!$data) {
            $data = self::where('id', $id)->first();
            app('cache')->tags(self::$cacheTag)->put($cacheName, $data, Config('cache.expireTime'));
        }

        return $data;
    }

    /**
     * @title   根据id数组，查找多条
     * @desc
     * @version 1.0.0
     * @level 1
     * @author {$author}
     * @package App\Models\Mongo
     * @since {$currentDate}
     * @params  type filedName required?
     * @param array $idList
     * @return mixed
     * @returns
     * []
     * @returns
     */
    static public function getByIdList(array $idList = [])
    {
        $cacheName = __METHOD__ . var_export($idList, TRUE);
        $data      = app('cache')->tags(self::$cacheTag)->get($cacheName);
        if (!$data) {
            $data = self::whereIn("id", $idList)->get();
            app('cache')->tags(self::$cacheTag)->put($cacheName, $data, Config('cache.expireTime'));
        }

        return $data;
    }

    /**
    * @title   根据third_id，查找多条
    * @desc
    * @version 1.0.0
    * @level 1
    * @author {$author}
    * @package App\Models\Mongo
    * @since {$currentDate}
    * @params  type filedName required?
    * @param array $params
    * @return mixed
    * @returns
    * []
    * @returns
    */
    static public function getByThirdIdList(array $params = [])
    {
        $cacheName = __METHOD__ . var_export($params, TRUE);
        $data      = app('cache')->tags(self::$cacheTag)->get($cacheName);
        if (!$data) {
            $data = self::Filter($params)->get();
            app('cache')->tags(self::$cacheTag)->put($cacheName, $data, Config('cache.expireTime'));
        }

        return $data;
    }

    /**
    * @title   添加数据
    * @desc
    * @version  1.0.0
    * @level 1
    * @author  {$author}
    * @package App\Models\Mongo
    * @since {$currentDate}
    * @params  type filedName required?
    * @param array $params
    * @return mixed
    * @returns
    * {}
    * @returns
    */
    static public function add(array $params)
    {
        $params['id'] = Helper::uuid();
        $params['created_at'] = date("Y-m-d H:i:s");
        $params['updated_at'] = $params['deleted_at'] = NULL;
        $data         = self::create($params);
        app('cache')->tags(self::$cacheTag)->flush();

        return $data;
    }

    /**
    * @title   修改记录
    * @desc
    * @version  1.0.0
    * @level 1
    * @author  {$author}
    * @package App\Models\Mongo
    * @since {$currentDate}
    * @params  type filedName required?
    * @param array $params
    * @return mixed
    * @returns
    * {}
    * @returns
    */
    static public function edit(array $params)
    {
        if(!isset($params['id'])){
            throw new \RuntimeException('id must exist', 2);
        }
        $record = self::where('id', $params['id'])->first();
        if (!$record) {
            throw new \RuntimeException("该数据不存在", 2);
        }
        $params['updated_at'] = date("Y-m-d H:i:s");
        $data = $record->update($params);
        app('cache')->tags(self::$cacheTag)->flush();

        return $data;
    }

    /**
    * @title    修改记录
    * @desc
    * @version  1.0.0
    * @level    1
    * @author  {$author}
    * @package App\Models\Mongo
    * @since {$currentDate}
    * @params   type filedName required?
    * @param array $params
    * @return mixed
    * @returns
    * {}
    * @returns
    */
    static public function updateByThirdIdAndSysId(array $params)
    {
        $params = Helper::preScopeFilter((new self)->casts, $params);

        $record = self::where('third_id', $params['third_id'])
            ->where('sys_id', $params['sys_id'])
            ->first();

        $params['updated_at'] = date("Y-m-d H:i:s");
        if (!$record) {
            $data = self::add($params);
        } else {
            $data = $record->update($params);
        }

        app('cache')->tags(self::$cacheTag)->flush();

        return $data;
    }

    /**
    * @title   删除记录
    * @desc
    * @version  1.0.0
    * @level 1
    * @author  {$author}
    * @package App\Models\Mongo
    * @since {$currentDate}
    * @params  type filedName required?
    * @param array $params
    * @return mixed
    * @returns
    * int
    * @returns
    */
    static public function remove(array $params = [])
    {
        if(!isset($params['idList']) || !is_array($params['idList'])){
            throw new \RuntimeException('idList must exist and it\'s array', 2);
        }
        $data = self::whereIn('id', $params['idList'])->delete();
        app('cache')->tags(self::$cacheTag)->flush();

        return $data;
    }

    /**
    * @title    删除记录根据third_id删除
    * @desc
    * @version  1.0.0
    * @level    1
    * @author  {$author}
    * @package App\Models\Mongo
    * @since {$currentDate}
    * @params   type filedName required?
    * @param array $params
    * @return mixed
    * @returns
    * int
    * @returns
    */
    static public function removeByThirdIdAndSysId(array $params = [])
    {
        if (!isset($params['thirdIdList']) || !is_array($params['thirdIdList'])) {
            throw new \RuntimeException('thirdIdList must exist and it\'s array', 2);
        }

        $data = self::whereIn('third_id', Helper::arrayValueToString($params['thirdIdList']))
            ->where('sys_id', $params['sys_id'])
            ->delete();

        app('cache')->tags(self::$cacheTag)->flush();

        return $data;
    }

}